//index.js
//获取应用实例
const app = getApp();
var QQMapWX = require('../../qqmap-wx-jssdk.min.js');
var qqmapsdk;

Page({
	data: {
		isPower: true,
		isMain: false,
		isShowList: true,
		isnoneList: false,
		isNums: 45210,
		index: null,
		StatusBar: app.globalData.StatusBar,
		CustomBar: app.globalData.CustomBar,
		userInfo: {},
		hasUserInfo: false,
		canIUse: wx.canIUse('button.open-type.getUserInfo'),
		region: [],
		cardCur: 0,
		swiperList: '',
		text: '欢迎来到星房惠，在这里你可以找到你想要的房源,可以看到不同的热点新闻资讯',
		marqueePace: 1,//滚动速度
		marqueeDistance: 0,//初始滚动距离
		marqueeDistance2: 0,
		marquee2copy_status: false,
		marquee2_margin: 60,
		size: 14,
		orientation: 'left',//滚动方向
		interval: 20, // 时间间隔
		picker: [],
		showcity: [],
		cityCode: '',
		hotnewsList: '',//热点资讯
		houseList: '',//楼盘列表
		loadModal: false,
		swiper: [
			{
				id: 1,
				photourl: '../../static/banner/banner1.jpg'
			},
			{
				id: 1,
				photourl: '../../static/banner/banner2.jpg'
			}
		],
	},


	//事件处理函数
	bindViewTap: function () {
		wx.navigateTo({
			url: '../logs/logs'
		})
	},

	RegionChange: function (e) {
		this.setData({
			region: e.detail.value
		})
	},
	onShow: function () {
		let vm = this;
		// vm.getUserLocation();
		var length = vm.data.text.length * vm.data.size;//文字长度
		var windowWidth = wx.getSystemInfoSync().windowWidth;// 屏幕宽度
		vm.setData({
			length: length,
			windowWidth: windowWidth,
			marquee2_margin: length < windowWidth ? windowWidth - length : vm.data.marquee2_margin//当文字长度小于屏幕长度时，需要增加补白
		});
		// vm.run1();// 水平一行字滚动完了再按照原来的方向滚动

	},

	run1: function () {
		var vm = this;
		var interval = setInterval(function () {
			if (-vm.data.marqueeDistance < vm.data.length) {
				vm.setData({
					marqueeDistance: vm.data.marqueeDistance - vm.data.marqueePace,
				});
			} else {
				clearInterval(interval);
				vm.setData({
					marqueeDistance: vm.data.windowWidth
				});
				vm.run1();
			}
		}, vm.data.interval);
	},

	getUserLocation: function () {
		wx.getSetting({
			success: (res) => {
				var vm = this;
				console.log(JSON.stringify(res))
				if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
					wx.showModal({
						title: '请求授权当前位置',
						content: '需要获取您的地理位置，请确认授权',
						success: function (res) {
							if (res.cancel) {
								wx.showToast({
									title: '拒绝授权',
									icon: 'none',
									duration: 1000
								})
							} else if (res.confirm) {
								wx.openSetting({
									success: function (dataAu) {
										if (dataAu.authSetting["scope.userLocation"] == true) {
											wx.showToast({
												title: '授权成功',
												icon: 'success',
												duration: 1000
											})
											//重新授权位置
											wx.getLocation({
												type: 'wgs84',
												success(res) {
													const latitude = res.latitude
													const longitude = res.longitude
													const speed = res.speed
													const accuracy = res.accuracy
													vm.getLocal(latitude, longitude)
													vm.setData({
														isMain: true,
														isPower: false,
													});
												}
											});


										} else {
											wx.showToast({
												title: '授权失败',
												icon: 'none',
												duration: 1000
											})
										}
									}
								})
							}
						}
					})
				} else if (res.authSetting['scope.userLocation'] == undefined) {
					//调用wx.getLocation的API
				}
				else {
					//调用wx.getLocation的API
					wx.getLocation({
						type: 'wgs84',
						success(res) {
							const latitude = res.latitude
							const longitude = res.longitude
							const speed = res.speed
							const accuracy = res.accuracy
							vm.getLocal(latitude, longitude)
							vm.setData({
								isMain: true,
								isPower: false,
							});
						}
					});
				}
			}
		})
	},

	onLoad: function () {
		qqmapsdk = new QQMapWX({
			key: 'XM4BZ-R5BHX-FIA4V-ZFFFN-QKEXO-3CFSP' //这里自己的key秘钥进行填充
		});
		if (app.globalData.userInfo) {
			this.setData({
				userInfo: app.globalData.userInfo,
				hasUserInfo: true,
				isMain: true,
				isPower: false,
			});
		} else if (this.data.canIUse) {
			// 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
			// 所以此处加入 callback 以防止这种情况
			app.userInfoReadyCallback = res => {
				this.setData({
					userInfo: res.userInfo,
					hasUserInfo: true,
					isMain: true,
					isPower: false,
				})
			}
		} else {
			// 在没有 open-type=getUserInfo 版本的兼容处理
			wx.getUserInfo({
				success: res => {
					app.globalData.userInfo = res.userInfo
					this.setData({
						userInfo: res.userInfo,
						hasUserInfo: true,
						isMain: true,
						isPower: false,
					})
				}
			})
		};
		this.getCity();
		this.getUserLocation();
		this.run1();
	},
	getUserInfo: function (e) {
		var vm = this;
		app.globalData.userInfo = e.detail.userInfo;
		if (e.detail.userInfo) {
			this.setData({
				userInfo: e.detail.userInfo,
				hasUserInfo: true,
				isMain: true,
				isPower: false,
			});
			wx.getLocation({
				type: 'wgs84',
				success(res) {
					const latitude = res.latitude
					const longitude = res.longitude
					const speed = res.speed
					const accuracy = res.accuracy
					vm.getLocal(latitude, longitude)
				}
			});
		}

		//用户授权之后获取Code 
		wx.login({
			success(res) {
				console.log('获取code');
				if (res.code) {
					// 发起网络请求
					var userCode = res.code;
					console.log('userCode:--' + userCode);
					//用户授权之后---获取用户信息存入数据库
					console.log('** user-info **');
					// console.log(app.globalData.userInfo);
					var UserInfo = app.globalData.userInfo;
					var opid = wx.getStorageSync('user').openid
					// wx.showLoading({
					// 	title: '加载中',
					// })
					app.core('post', 'create_xcx_user', {
						'open_id': opid,
						'nickname': UserInfo.nickName,
						'headpic': UserInfo.avatarUrl,
						'js_code': userCode
					}, (res) => {
						console.log('存库成功')
						console.log(res);
						wx.hideLoading()
					},
						(err) => {
							console.log(err)
						}
					)

				} else {
					console.log('登录失败！' + res.errMsg)
				}
			}
		});
	},

	//获取用户当前位置
	getLocal: function (latitude, longitude) {
		let vm = this;
		qqmapsdk.reverseGeocoder({
			location: {
				latitude: latitude,
				longitude: longitude
			},
			success: function (res) {
				//console.log(JSON.stringify(res));
				let province = res.result.ad_info.province
				let city = res.result.ad_info.city.split("市", 1)
				let area = res.result.ad_info.district
				vm.setData({
					region: [province, city, area] //赋值当前位置信息
				});

				//拿到定位当前的位置与后台给的站点匹配，没有的话默认显示合肥340100
				var crrentCity = vm.data.region[1][0];
				//获取后台给的匹配城市
				// wx.showLoading({
				// 	title: '加载中',
				// })
				app.core('get', 'get_all_sites', {
					// data 部分
				}, (res) => {
					wx.hideLoading()
					var newList = [];
					for (var k = 0; k < res.data.length; k++) {
						newList.push(res.data[k].area)
					}
					var ifHave = newList.indexOf(crrentCity);//查找当前的城市是否在匹配的城市下，不存在返回 -1， 存在返回当前的索引
					if (ifHave == -1) {
						vm.setData({
							region: [province, '合肥', area] // 不存在匹配城市的时候，左上角定位默认显示合肥
						});

						// 不存在匹配城市的时候，默认显示合肥的 推荐楼盘、广告、热点资讯
						vm.hotNews("340100");
						vm.getAdvert("340100");
						vm.houseList("340100");
					} else {
						// 找到匹配城市的时候，显示对应城市的 推荐楼盘、广告、热点资讯
						var hasCity = vm.data.region[1][0];
						console.log('找到了对应的城市并打印出来');
						var cityCode = res.data[ifHave].id; //根据当前的数组索引找到对应的值，res.data服务端的返回list
						console.log(cityCode)
						vm.hotNews(cityCode);
						vm.getAdvert(cityCode);
						vm.houseList(cityCode);
					}
				},
					(err) => {
						console.log(err)
					}
				)
			},
			fail: function (res) {
				console.log(res);
			},
			complete: function (res) {
				// console.log(res);
			}
		});
	},

	DotStyle(e) {
		this.setData({
			DotStyle: e.detail.value
		})
	},
	cardSwiper(e) {
		this.setData({
			cardCur: e.detail.current
		})
	},

	//跳转
	navigateTotab: function (e) {
		// console.log(e);
		var toUrl = e.currentTarget.dataset.url;
		// console.log(toUrl);
		wx.switchTab({
			url: toUrl
		});
	},
	navigateTo: function (e) {
		// console.log(e);
		var toUrl = e.currentTarget.dataset.url;
		// console.log(toUrl);
		wx.navigateTo({
			url: toUrl
		});
	},

	gotoList: function (e) {
		wx.switchTab({
			url: e.currentTarget.dataset.url
		});
	},

	gotohouseList: function (e) {
		wx.switchTab({
			url: e.currentTarget.dataset.url
		});
	},

	//获取城市
	getCity: function () {
		wx.showLoading({
			title: '加载中',
		})
		// 获取城市
		var vm = this;
		app.core('get', 'get_all_sites', {
			// data 部分
		}, (res) => {
			// wx.showLoading({
			// 	            title: '加载中',
			//           })
			var picker = vm.data.picker;
			var citylist = [];
			var showcitylist = [];
			for (var i = 0; i < res.data.length; i++) {
				citylist.push({
					name: res.data[i].area,
					id: res.data[i].id
				});
				showcitylist.push(res.data[i].area);
			}
			vm.setData({
				picker: citylist,
				showcityCode: showcitylist
			});
			wx.hideLoading()
		},
			(err) => {
				console.log(err)
			}
		)
	},

	//选择城市
	PickerChange(e) {
		var vm = this;
		var picker = vm.data.picker;
		var cityCode = vm.data.cityCode;
		for (var j = 0; j < picker.length; j++) {
			if (j == e.detail.value) {
				vm.setData({
					cityCode: picker[j].id,
					index: e.detail.value
				});
				app.globalData.cityCode = picker[j].id;// 修改全部变量 cityCode， 后面进入页面获取城市code用
				vm.setData({
					loadModal: true
				})
				setTimeout(function () {
					vm.setData({
						loadModal: false
					})
				}, 3000)

				//切换城市获取对应的数据
				vm.getAdvert(picker[j].id);   //广告获取
				vm.hotNews(picker[j].id);   //热点资讯
				vm.houseList(picker[j].id);   //推荐楼盘列表
			}
		}
	},

	//广告获取
	getAdvert: function (cityCode) {
		var vm = this;
		wx.showLoading({
			title: '加载中',
		})
		app.core('get', 'get_advert/site_id/' + cityCode, {
			// data 部分
		}, (res) => {
			var swiperList = vm.data.swiperList;
			var advertlist = [];
			for (var i = 0; i < res.data.length; i++) {
				advertlist.push({
					id: res.data[i].id,
					type: 'image',
					url: res.data[i].photourl,
					tourl: res.data[i].redirecturl
				})
			}
			vm.setData({
				swiperList: advertlist
			});
			wx.hideLoading()
		},
			(err) => {
				console.log(err)
			}
		)
	},
	//热点资讯
	hotNews: function (cityCode) {
		var vm = this;
		wx.showLoading({
			title: '加载中',
		})
		app.core('get', 'get_home_hot_news/site_id/' + cityCode, {
			// data 部分
		}, (res) => {
			var hotnewsList = vm.data.hotnewsList;
			vm.setData({
				hotnewsList: res.data
			})
			wx.hideLoading()
		},
			(err) => {
				console.log(err)
			}
		)

	},
	//进入热点资讯 详情
	gethotDesc: function (e) {
		console.log(e);
		var id = e.currentTarget.dataset.id
		wx.navigateTo({
			url: '/pages/information/detail?id=' + id,
		})
	},

	//推荐楼盘列表
	houseList: function (cityCode) {
		var vm = this;
		wx.showLoading({
			title: '加载中',
		})
		app.core('get', 'get_home_houses/site_id/' + cityCode, {
			// data 部分
		}, (res) => {
			var houseList = vm.data.houseList;
			vm.setData({
				houseList: res.data
			})
			wx.hideLoading()
		},
			(err) => {
				console.log(err)
			}
		)
	},

	//楼盘搜索
	loupanSearch: function (e) {
		var cityCode = app.globalData.cityCode; //全局动态获取当前的城市id 
		var vm = this;
		var currentVal = (e.detail.value).replace(/\s+/g, ''); //当前输入的关键字
		if (currentVal == '') {
			wx.showToast({
				title: '请输入有效查询条件',
				duration: 2000,
				icon: 'none'
			});
			vm.setData({
				isShowList: true,
				isnoneList: false
			});
			vm.houseList(cityCode);
			return;
		}
		app.core('get', 'search_tj_by_name/site_id/' + cityCode, {
			keywords: currentVal
		}, (res) => {
			console.log('搜索返回');
			console.log(res);

			if (res.resultCode == 200) {
				console.log(res.data.length);
				if (res.data.length > 0) {
					vm.setData({
						isShowList: true,
						isnoneList: false
					});
					wx.showLoading({
						title: '努力加载中...',
					});
					setTimeout(function () {
						wx.hideLoading();
						vm.setData({
							houseList: res.data
						})
					}, 3000);

				} else {
					vm.setData({
						isShowList: false,
						isnoneList: true
					});
				}
			}
		},
			(err) => {
				console.log(err)
			}
		)

	},

})
